package com.ray.study.sample.test.spock.service

import com.ray.study.sample.test.spock.entity.User
import com.ray.study.sample.test.spock.mapper.UserMapper
import com.ray.study.sample.test.spock.service.impl.UserServiceImpl
import spock.lang.Specification
import spock.lang.Unroll

/**
 * UserServiceSpec
 *
 * @author ray* @date 2020/5/16
 */
class UserServiceSpec extends Specification {

    @Unroll
    def "Query user by id=#id and username=#username"() {
        given: "a mock user maper"
        //mock
        UserMapper userMapper = Mock(UserMapper.class)
        //stub
        userMapper.findById(_) >> User.builder().id(id+100).build();
        userMapper.findByUserName(_) >> User.builder().username(username+"100").build()

        and: "an  userService"
        def userService = new UserServiceImpl(userMapper)

        when: "query user"
        def user = userService.query(User.builder().id(id).username(username).build())

        then:
        with(user){
            user.id == resId
            user.username == resUserName
        }

        where:
        id   |  username     ||  resId  |  resUserName
        0    |  null         ||  100    |  null
        1    |  null         ||  101    |  null
        -1   |  "tom"        ||  null   |  "tom100"
        -1   |  "jack"       ||  null   |  "jack100"

    }

    def "Save user"() {
        given: "mock user maper"
        //mock
        UserMapper userMapper = Mock(UserMapper.class);
        def userService = new UserServiceImpl(userMapper)

        when: "add user"
        userService.save(User.builder().id(1).username("tom").build())

        then:
        1 * userMapper.save(_)
    }

}
